package com.hitrust.gs.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLDecoder;

import org.apache.log4j.Logger;

import com.hitrust.gs.lib.GSLogWriter;

public class HttpConnection
{
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger("socket");
    
    
	/**
	 * 远程Servlet
	 */
	private String sHost = "";

    
	/**
	 * 发送请求
	 * @param params
	 * @return state code
	 */
	public String doGet(String params)
	{
		InputStream inputStream = null;
		BufferedReader bufferedReader = null;
		String result = "";
		try
		{
			// 组成发送的URL字符串
			String sUrl = new StringBuffer(sHost).append(params).toString();
			// URL类型
			URL webUrl = new URL(sUrl);
			// 连接
			HttpURLConnection httpURLConnection = (HttpURLConnection) webUrl
					.openConnection();

			// 得到返回值
			result = httpURLConnection.getRequestProperty("result");
			
			if (result == null)
					result = "";
			 
		} catch (MalformedURLException e)
		{
			logger.error("无效的URL", e);
		} catch (IOException e)
		{
			logger.error("IO错误", e);
		}

		return result;

	}
	
	/**
	 * 发送请求
	 * @param params
	 * @return state code
	 */
	public String doPost(String params)
	{
		InputStream inputStream = null;
		BufferedReader bufferedReader = null;
		String result = "";
		try
		{
			// 组成发送的URL字符串
			String sUrl = new StringBuffer(sHost).toString();
			// URL类型
			URL webUrl = new URL(sUrl);
			// 连接
			HttpURLConnection httpURLConnection = (HttpURLConnection) webUrl
					.openConnection();
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);

			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.getOutputStream().write(params.getBytes());
			httpURLConnection.getOutputStream().flush();
			httpURLConnection.getOutputStream().close();			

			// 得到返回值
			result = httpURLConnection.getInputStream().toString();
			
			if (result == null)
					result = "";
			 
		} catch (MalformedURLException e)
		{
			logger.error("无效的URL", e);
		} catch (IOException e)
		{
			logger.error("IO错误", e);
		}

		return result;

	}	
	
	
	
	/**
	 * POST方式发送交易数据
	 * @param pRemoteURL 远端服务器地址
	 * @param pParam 需发送的字符串
	 * @return http返回码 
	 */
	public String postMessage(String pRemoteURL, String pParam) {
	
	InputStream inputStream = null;
	BufferedReader bufferedReader = null;
	StringBuffer sb = null;
	HttpURLConnection httpURLConnection = null;
	try {
		// URL转码
		String encodeStr = urlEncodeForPost(pParam);
//		String encodeStr = pParam;
	    
		URL url = new URL(pRemoteURL);
		httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setDoInput(true);

		// 设置发送方式为POST
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");

		// 发送数据
		httpURLConnection.getOutputStream().write(encodeStr.getBytes());
		httpURLConnection.getOutputStream().flush();
		httpURLConnection.getOutputStream().close();

		// 得到返回值
		inputStream = httpURLConnection.getInputStream();
		bufferedReader = new BufferedReader(new InputStreamReader(
			inputStream));

		String line;
		sb = new StringBuffer();
		while ((line = bufferedReader.readLine()) != null) {
		sb.append(line);
		}

		return sb.toString();


	} catch (ProtocolException e) {
		GSLogWriter.error(logger,e.getLocalizedMessage());
		return HttpServiceServlet.FAIL;
	} catch (IOException e) {
		GSLogWriter.error(logger,e.getLocalizedMessage());
		return HttpServiceServlet.FAIL;
	} catch(Exception e) {
		GSLogWriter.error(logger,e.getLocalizedMessage());
		return HttpServiceServlet.FAIL; 
	} finally {
		if (httpURLConnection != null)
		httpURLConnection.disconnect();
	}

	}
	
	
	/**
	 * GET方式发送数据
	 */
	public String getMessage(String pRemoteURL, String pParam) {

	InputStream inputStream = null;
	BufferedReader bufferedReader = null;
	StringBuffer sb = null;
	HttpURLConnection httpURLConnection = null;
	try {
		// URL转码
		String encodeStr = urlEncode(pParam);
	    
		// 组成发送的URL字符串
		String sUrl = new StringBuffer(pRemoteURL).append("?").append(
			encodeStr).toString();

		// URL类型
		URL url = new URL(sUrl);
		// 连接
	    
		httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.addRequestProperty("content-type","text/html;charset=UTF-8");
		httpURLConnection.connect();

		// 得到返回值
		inputStream = httpURLConnection.getInputStream();
		bufferedReader = new BufferedReader(new InputStreamReader(
			inputStream));

		String line;
		sb = new StringBuffer();
		while ((line = bufferedReader.readLine()) != null) {
		sb.append(line);
		}

		return sb.toString();
	} catch (MalformedURLException e) {
		GSLogWriter.error("无效的URL",e.getLocalizedMessage());
		return HttpServiceServlet.FAIL;
	} catch (IOException e) {
		GSLogWriter.error(logger,e.getLocalizedMessage());
		return HttpServiceServlet.FAIL;
	} finally {
		if (httpURLConnection != null)
		httpURLConnection.disconnect();
	}
	}

	/**
	 * 字符串结束标志 APEP-->GS
	 */
	private static final String END_TAG = "end";	
	
	/**
	 * URL编码
	 * 按照UTF-8编码
	 * 专用于POST参数提交时,只编码value而不编码name
	 * @param pSource 源字符串
	 * @return 编码后的字符串
	 */
	public static String urlEncodeForPost(String pSource) throws Exception {
	if(pSource == null)
		return null;
	StringBuffer result = new StringBuffer("");
	String sFirstClassSep = "&";
	String sSecondClassSep = "=";
	String[] tFirstClassArray = pSource.split(sFirstClassSep);
	for(int i=0; i<tFirstClassArray.length; i++) {
		String tTempString = tFirstClassArray[i];
	    
		int index = tTempString.indexOf(sSecondClassSep);
	    
		if(END_TAG.equalsIgnoreCase(tTempString)) {
		result.append(END_TAG);
		continue;
		}
	    
		if(index == -1)
		throw new Exception("不符合规格的字符串.");
	    
		String tName = tTempString.substring(0, index);
		String tValue = "";
		if(index != tTempString.length())
		tValue = tTempString.substring(index+1);
	    
		result.append(tName).append(sSecondClassSep);
		result.append(urlEncode(tValue));
		result.append(sFirstClassSep);
	}
	return result.toString();
	}
	
   
	/**
	 * URL编码
	 * 按照UTF-8编码
	 * @return 编码后的字符串
	 */
	public static String urlEncode(String pSource) throws UnsupportedEncodingException {
		String result = URLEncoder.encode(pSource, "UTF-8");
		return result;
	}
    
	/**
	 * URL解码
	 * 按照UTF-8解码
	 * @return 解码后的字符串
	 */
	public static String urlDecode(String pSource)
		throws UnsupportedEncodingException {
//	String result = new String(pSource.getBytes("UTF-8"), "GBK");
	String result = URLDecoder.decode(pSource, "UTF-8");
	return result;
	}    

}
